package com.wedo.search.service;

import com.wedo.book.pojo.Author;
import com.wedo.book.pojo.Book;
import com.wedo.common.pojo.PageResult;
import com.wedo.search.client.AuthorClient;
import com.wedo.search.client.BookClient;
import com.wedo.search.pojo.BookSearchRequest;
import com.wedo.search.pojo.SearchBook;
import com.wedo.search.repository.BookRepository;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

@Service
public class SearchService {
    @Autowired
    private BookClient bookClient;

    @Autowired
    private AuthorClient authorClient;

    @Autowired
    private BookRepository bookRepository;

    public SearchBook buildSearchBook(Book book) {
        SearchBook searchBook = new SearchBook();
        searchBook.setId(book.getId());
        searchBook.setTitle(book.getTitle());
        searchBook.setImage(book.getImage());
        Author author = authorClient.queryAuthorByAid(book.getaId());
        searchBook.setAuthorName(author.getName());
        searchBook.setAll(book.getTitle() + " " + author.getName());
        return searchBook;

    }

    public PageResult<SearchBook> search(BookSearchRequest request) {
        if (StringUtils.isBlank(request.getKey())) {
            return null;
        }
        // 自定义查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加查询条件
        QueryBuilder basicQuery = QueryBuilders.matchQuery("all", request.getKey()).operator(Operator.AND);
        queryBuilder.withQuery(basicQuery);
        // 添加分页
        queryBuilder.withPageable(PageRequest.of(request.getPage() - 1,request.getSize()));
        Page<SearchBook> searchPage = this.bookRepository.search(queryBuilder.build());

        return new PageResult<SearchBook>(searchPage.getTotalElements(),searchPage.getTotalPages(),searchPage.getContent());
    }

    public void save(Long id) {
        // 查询book
        Book book = bookClient.queryBookByBid(id);
        // 查询作者
        Author author = authorClient.queryAuthorByAid(book.getaId());
        // 封装成searchBook
        SearchBook searchBook = new SearchBook();
        searchBook.setId(book.getId());
        searchBook.setTitle(book.getTitle());
        searchBook.setImage(book.getImage());
        searchBook.setAuthorName(author.getName());
        searchBook.setAll(book.getTitle() + " " + author.getName());
        // 保存
        bookRepository.save(searchBook);
    }


    public void delete(Long id) {
        bookRepository.deleteById(id);
    }
}
